package com.example.auth.handler;

import com.example.auth.util.JsonUtils;
import com.example.common.constant.ServiceConstants;
import com.example.common.dto.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Authentication failure processor after login
 *
 * @author cuihaida
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        // clear security context
        SecurityContextHolder.clearContext();

        // judge exception
        int code = ServiceConstants.RESPONSE_FAIL;
        String msg = "error";
        if (e instanceof UsernameNotFoundException) {
            msg = "username and password error！";
        } else if (e instanceof BadCredentialsException) {
            msg = "username and password error！";
        } else if (e instanceof DisabledException) {
            msg = "username and password error！";
        } else if (e instanceof CredentialsExpiredException) {
            msg = "username and password error！";
        } else if (e instanceof LockedException) {
            msg = "username and password error！";
        } else if (e instanceof AccountExpiredException) {
            msg = "username and password error！";
        } else if (e instanceof InternalAuthenticationServiceException) {
            msg = "auth error！";
        }

        // return client
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        out.write(JsonUtils.toString(Result.error(code, msg)).getBytes());
        out.flush();
        out.close();
    }
}
